//
//  ChooseLocalPhotoLibView.m
//  A段项目
//
//  Created by dllo on 16/1/28.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ChooseLocalPhotoLibView.h"
#import "ChoosePictureCell.h"
#import "upLoadForSecond.h"
#import "FifthViewOfUploadPictureViewController.h"


@interface ChooseLocalPhotoLibView () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrForImage;

@property (nonatomic, retain) NSData *data;

@property (nonatomic, retain) NSArray *array;

@end

@implementation ChooseLocalPhotoLibView

{
    int count;  //用来表示右上角的颜色,表示当前有无照片选中
    
}


- (void)dealloc {
    
     [[NSNotificationCenter defaultCenter] removeObserver:self]; /*移除通知中心.*/
    
    [_arrForImage release];
    [_arrLocalPic release];
    
    [_collectionView release];
    
    [super dealloc];
    
}

- (NSArray *)dataArrImage {
    
    if (self.arrForImage == nil) {
        
        self.arrForImage = [NSMutableArray array];
    }
    
    return self.arrForImage;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
   
   
    [self changeNavi];
    
    [self createCollectionView];
    
    [self dataArrImage];
    
    [self ChooseState];
    
    [self imageData];
    
    
   self.array = [NSArray arrayWithArray:self.arrLocalPic];
    

    
}

- (NSData *)imageData {
    
    if (self.data == nil) {
        
        self.data = [NSData data];
     
        return self.data;
    }else {
        
        
        return self.data;
    }
    
    
}

/**利用通知中心通知图片选中状态. */
- (void)ChooseState {
    
    /**接收选中的信息. */
    [[NSNotificationCenter defaultCenter] addObserverForName:@"add" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        /*用来控制右上角按钮颜色. */
        count ++ ; //选中时,计数加一
        
       self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        
        [self.arrForImage addObject:[note.userInfo objectForKey:@"item"]]; /*将图片添加到数组里*/
        
    }];
 
    
    /**接收取消选中的通知. */
    [[NSNotificationCenter defaultCenter] addObserverForName:@"sub" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        count --; //取消选中时 计数减一.
        
        
        [self.arrForImage removeObject:[note.userInfo objectForKey:@"item1"]];
        
        if (count != 0) {
            
            
            
        }
        
        
        /**判断当没有照片被选中是. 右上角文字颜色变灰*/
        if (count == 0) {
            
            self.navigationItem.rightBarButtonItem.tintColor = [UIColor grayColor];
            
        }
    }];
}

#pragma mark -- 修改导航栏属性.
- (void)changeNavi {

    self.navigationItem.title = @"选择图片";
    
    self.navigationController.navigationBar.backItem.title = @"取消";
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"上传" style:1 target:self action:@selector(finishAction)];
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor grayColor];


}

#pragma mark -- 创建 collectionView.
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowlayout];
    flowlayout.scrollDirection = 0;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    flowlayout.sectionInset = UIEdgeInsetsMake(10, 20, 5, 20);
    
    flowlayout.itemSize = CGSizeMake((self.view.frame.size.width - 8)/4, (self.view.frame.size.width - 8)/4);
    
    
    self.collectionView.delegate = self;
    
    self.collectionView.dataSource = self;
    
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[ChoosePictureCell class] forCellWithReuseIdentifier:@"pool1"];
    
    [_collectionView release];
    
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    

    
    return self.arrLocalPic.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UIImage *image = [self.arrLocalPic objectAtIndex:indexPath.item];
    
    ChoosePictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
    

    
    [cell passedInfo:image];
    
    return cell;
    
}

#pragma mark -- 上传 按钮的点击事件.
- (void)finishAction {
    
    
    NSLog(@"----%ld",self.arrForImage.count);
    
    /**当前有照片被选中时. */
    if (count > 0) {
        
        
        
      //  UIImage *image = [self.arrForImage firstObject]; //取出添加的第一张照片
        
        FifthViewOfUploadPictureViewController *fifUpLoad = [[FifthViewOfUploadPictureViewController alloc] init];
        
        fifUpLoad.arrImage = [NSMutableArray array];
        
        
        __block typeof(self)weakSelf = self;
        for (UIImage *image in self.arrForImage) {
            
            NSInteger count1 = [self.array indexOfObject:image]; //获取下标
            
            PHAsset *asset = [self.arrForAsset objectAtIndex:count1]; //获取原始的图片资源
            
            PHCachingImageManager *cache = [[PHCachingImageManager alloc] init];
            
           [cache requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
               
                   [fifUpLoad.arrImage addObject:[UIImage imageWithData:imageData]];
                
               if (fifUpLoad.arrImage.count == self.arrForImage.count) {
                   
                   UIImage *image = [UIImage imageNamed:@"jia"];
                   
                   [fifUpLoad.arrImage addObject:image];
            
                   [weakSelf.navigationController pushViewController:fifUpLoad animated:YES];
                   
                   [fifUpLoad release];
                   
               }
               
               
           }];
            
            
            
        }
        
        
        
        
        
        
        
//        [self.navigationController pushViewController:fifUpLoad animated:YES];
//        
//        
//        [fifUpLoad release];
        
        
        
//        NSInteger count1 = [self.array indexOfObject:image]; //获取下标
//        
//        PHAsset *asset = [self.arrForAsset objectAtIndex:count1]; //获取原始的图片资源
//        
//        PHCachingImageManager *cache = [[PHCachingImageManager alloc] init];
//        
//        /**获取高质量图片*/
//        [cache requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//            
//            /**上传图片. */
//            upLoadForSecond *upload = [[upLoadForSecond alloc] init];
//            
//            upload.imageView = [[UIImageView alloc] initWithImage:[self.arrForImage objectAtIndex:0]];
//            
//            upload.arrImage = [NSArray arrayWithArray:self.arrForImage];
//            
//            upload.image = [UIImage imageWithData:imageData];
//            
//            [self.navigationController pushViewController:upload animated:YES];
//            
//            [upload.imageView release];
//
//            
//        }];

        
        
    }else {
        /**没有照片选中时,弹出警告栏. */
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您必须选择一张图片" preferredStyle:1];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:1 handler:nil];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    
    /**当此界面推出到上一个界面时,将所有的状态进行初始化设置. */
    [[NSNotificationCenter defaultCenter] addObserverForName:@"viewAppeared" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor grayColor];
        /**初始化状态. */
        self.tabBarController.tabBar.hidden = YES;
        
        [self.arrForImage removeAllObjects];
        
        count = 0;
        
    }];
    
    self.tabBarController.tabBar.hidden = YES;
    
    
}

- (void)viewDidDisappear:(BOOL)animated {
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
